<?php

namespace App\Service\CommodityService;

use App\Service\AppService\SystemCacheConfigService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\CommodityModel\SupplierCompany;
use Hyperf\DbConnection\Db;

/**
 * 行云供应商商品资料拉取
 * @author chenshubo
 */
class SupplierCommodityXingyunPullLogService extends BaseService
{
    const PULL_FLAG = 'shopxingyun';
    const TIME_WAIT = 360; //分钟
    const PULL_USER_COUNT = 10; //每次同时拉取供应商的数量

    /**
     * 开启计划任务
     */
    public function runTask($pullFlag = '')
    {
        $config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('channel_task_user_limit');
        if (empty($config)) {
            return Normal::returnCode(Normal::FAIL, '参数未配置');
        }
        //所有供应商拉取完成间隔时间
        $SupplierPullWaitTime = self::TIME_WAIT;
        //预计下次拉取商品时间
        $CommodityGetNetPeriod = date("Y-m-d H:i:s", time() + $SupplierPullWaitTime * 60);

        $supplierCode = $pullFlag ?: self::PULL_FLAG;
        $res = SupplierCommodityPullLogService::instance()->getWaitPullSupplierWareHouseInfosByThirdPartyPlatformCode($supplierCode);
        if ($res['code'] != Normal::SUC) {
            return $res;
        }


        $suppliers = $res['data'];

        //获取供应商参数
        $SupplierIDs     = array_column($suppliers, 'SupplierID');
        //初始化拉取状态
        $updateArr = [
            'CommodityGetTaskStatus'    => 0,
            'CommodityGetFinishCount'   => 0,
            'CommodityGetFinishUseTime' => 0.000,
        ];
        SupplierCompany::instance()->whereIn('ID', $SupplierIDs)->update($updateArr);


        foreach ($suppliers as $supplier) {
            //获取供应商参数
            $company_code   = $supplier['ThirdPartyPlatformCode'] ? $supplier['ThirdPartyPlatformCode'] : $supplier['SupplierCode'];
            $SupplierID     = $supplier['SupplierID'];
            $CommodityGetStartTime = microtime(true);

            //获取行云的所有分类
            $apiBody = $supplier['JsonBody'];
            $routerClass = '\\App\\Service\\OrderService\\OrderRouteService\\' . ucfirst($company_code);
            $queryCategory = $routerClass::instance()->queryGoodsCategory([
                'apiBody'   => $apiBody,
                'queryBody' => []
            ]);

            if ($queryCategory['code'] != Normal::SUC) {
                return $queryCategory;
            }

            if (empty($queryCategory['data']['category_list'])) {
                return Normal::returnCode(Normal::FAIL, "当前行云分类获取异常");
            }


            //处理分类拉取情况
            $page = 1;
            $currentLastPage = $currentPage  = $CommodityGetTotal = 0;
            foreach ($queryCategory['data']['category_list'] as $page_key => $cate_item) {
                $innerPage = 1;
                while (true) {
                    //根据分类获取商品
                    $queryBody = [
                        'page'          => $innerPage,
                        'limit'         => isset($apiBody['limit']) ? $apiBody['limit'] : 100,
                        'category_id'   => $cate_item['category_id']
                    ];

                    try {
                        $resQuery = $routerClass::instance()->queryGoodsList(['apiBody'   => $apiBody, 'queryBody' => $queryBody]);
                        if ($resQuery['code'] != Normal::SUC) {
                            SupplierCompany::instance()->where('ID', $SupplierID)->update(['CommodityGetContents' => $resQuery['msg'], 'CommodityGetTaskStatus' => 3]);
                            break;
                        }
                        SupplierCompany::instance()->where('ID', $SupplierID)->update(['CommodityGetContents' => $resQuery['msg']]);
                    } catch (\Throwable $t) {
                        SupplierCompany::instance()->where('ID', $SupplierID)->update(['CommodityGetContents' => $t->getMessage(), 'CommodityGetTaskStatus' => 3]);
                        break;
                    }

                    //动态更新已拉取的数据
                    $pull_count = count($resQuery['data']['list']);
                    $CommodityGetTotal += $pull_count;
                    $updateArr = [
                        'CommodityGetTaskStatus'    => 1,
                        'CommodityGetFinishCount'   => Db::raw("CommodityGetFinishCount+{$pull_count}")
                    ];
                    SupplierCompany::instance()->where('ID', $SupplierID)->update($updateArr);
                    $currentPage = ($page * $page_key) + $innerPage + $currentLastPage;
                    $MessageBody  = [
                        'SupplierID'        => $SupplierID,
                        'SupplierCode'      => $company_code,
                        'IsFirstPage'       => $currentPage == 1 ? 1 : 0,
                        'DataPage'          => $currentPage,
                        'IsLastPage'        => 0,
                        'GoodsItemList'     => $resQuery['data']['list']
                    ];
                    SupplierCommodityPullLogService::instance()->publish($MessageBody);

                    //如果获取数据发送至消息队列，发送批量
                    if ($resQuery['data']['has_next'] == false) {
                        $currentLastPage = $currentPage;
                        break;
                    }

                    $innerPage++;
                }
            }

            //更新总数量
            $MessageBody  = [
                'SupplierID'        => $SupplierID,
                'SupplierCode'      => $company_code,
                'IsFirstPage'       => 0,
                'DataPage'          => 1,
                'IsLastPage'        => 1,
                'GoodsItemList'     => []
            ];
            SupplierCommodityPullLogService::instance()->publish($MessageBody);

            //拉取完成
            $updateArr = [
                'CommodityGetTaskStatus'    => 2,
                'CommodityGetContents'      => '拉取完成',
                'CommodityGetFinishUseTime' => bcsub(microtime(true), $CommodityGetStartTime, 3),
                'CommodityGetNetPeriod'     => $CommodityGetNetPeriod
            ];
            SupplierCompany::instance()->where('ID', $SupplierID)->update($updateArr);
        }

        return Normal::returnCode(Normal::SUC, '拉取完成');
    }
}
